@using DashboardService.Api.Queries
<Card>
    <CardHeader>
        Products sales
    </CardHeader>
    <CardBody>
        <PieChart
            Options="options"
            OptionsObject="new { animation = new { duration = 0 }, hover = new { animationDuration = 0 }, responsiveAnimationDuration = 0 }" 
            TItem="decimal"
            @ref="pieChart">

        </PieChart>
    </CardBody>
</Card>

@code {
    [Parameter]
    public DateTime PeriodFrom { get; set; }
    
    [Parameter]
    public DateTime PeriodTo { get; set; }
    
    [Inject]
    private DashboardClient DashboardClient { get; set; }
    
    private PieChart<decimal> pieChart;

    private PieChartOptions options = new ()
    {
        Responsive = true,
        MaintainAspectRatio = false
    };
    
    protected override async Task OnAfterRenderAsync( bool firstRender )
    {
        if (firstRender)
        {
            await Redraw();
        }
    }

    private async Task Redraw()
    {
        var salesData = await LoadData();
        
        await pieChart.Clear();

        var labels = salesData.PerProductTotal.Select(p => p.Key).ToList();
        var data = salesData.PerProductTotal.Select(p => p.Value.PremiumAmount).ToList();

        await pieChart.AddLabelsDatasetsAndUpdate
            (
                labels,
                new PieChartDataset<decimal>()
                {
                    Label = "Products sales (EUR)",
                    Data = data,
                    BorderWidth = 1,
                    BackgroundColor = new string[]
                    {
                        "rgb(255, 99, 132)",
                        "rgb(54, 162, 235)",
                        "rgb(255, 205, 86)",
                        "rgb(76, 155, 32)"
                    },
                    HoverOffset = 4
                }
            );

    }

    private async Task<GetTotalSalesResult> LoadData()
    {
        var totalSales = await DashboardClient.GetTotalSales(new GetTotalSalesQuery
        {
            SalesDateFrom = PeriodFrom,
            SalesDateTo = PeriodTo
        });

        return totalSales.Result;
    }

}